<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <l-panel>
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('please enter关键字')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <el-button-group v-if="lr_hasPageAuth('Sync','buttons')">
            <!-- <el-button type="warning" size="mini" @click="openFrom()" icon="el-icon-refresh">{{ $t("同步") }}</el-button> -->
          </el-button-group>
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        ref="mainTable"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableShowData"
        :loading="loading"
        rowKey="f_CompanyId"
        pidKey="f_ParentId"
        isTree
        default-expand-all>
        <template v-slot:f_FoundedTime="scope">
          {{ lr_dateFormat(scope.row.f_FoundedTime, "yyyy-MM-dd") }}
        </template>
        <template v-slot:f_Nature="scope">
          {{
            lr_dataItemName(lr_dataItem["CompanyNature"], scope.row.f_Nature)
          }}
        </template>
        <l-table-btns
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <l-dialog
      :height="550"
      :title="formTitle"
      :visible.sync="formVisible"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form ref="form"></my-form>
    </l-dialog>

      <!-- 同步操作 -->
      <l-dialog :title="$t(syncTitle)"
          :visible.sync="syncVisible"
          :height="150"
          :width="400"
          @ok="handleSync"
          >
          <div class="l-from-body">
              <el-form size="small" ref="syncForm" label-width="100px">
                  <el-col :span="24">
                      <el-form-item label="截止时间" prop="startTime">
                          <l-date format="yyyy-MM-dd HH:mm:ss" dateType="datetime" :clearable="true"
                          v-model="startTime" :placeholder="$t('please select')"/>
                      </el-form-item>
                  </el-col>
              </el-form>
          </div>
      </l-dialog>

  </l-layout>
</template>

<script>
const api = window.$api.organization.company;

import MyForm from "./form";
export default {
  components: {
    MyForm,
  },
  data() {
    return {
      lr_isPage: true,
      //query
      searchWord: "",
      searchTableData: null,

      loading: false,
      columns: [
        { label: "名称", prop: "f_FullName", minWidth: "260" },
        { label: "编码", prop: "f_EnCode", width: "150" },
        { label: "简称", prop: "f_ShortName", width: "150" },
        { label: "排序", prop: "f_SortCode", width: "80", align: "center" },
        { label: "时间", prop: "f_FoundedTime", width: "100", align: "center" },
        {
          label: "负责人",
          prop: "f_Manager",
          width: "80",
          align: "center",
          dataType: "user",
        },
      ],
      tableBtns: [
        { prop: "Edit", label: this.$t("Edit"),width:40 },
        { prop: "Delete", label: this.$t("Delete"),width:40 },
      ],
      tableData: [],

      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      syncLoading:false,
      syncVisible:false,
      syncTitle:this.$t("指定更新截止时间"),
      startTime:""
    };
  },
  mounted() {
    this.lr_loadDataItem("CompanyNature");
    this.loadTable();
  },
  computed: {
    tableShowData() {
      if (this.searchTableData) {
        return this.searchTableData; ///this.$toTree(this.searchTableData,"f_CompanyId","f_ParentId","f_CompanyId","f_FullName")
      } else {
        return this.lr_companyList; //this.lr_companyTree
      }
    },
  },
  methods: {
    async loadTable() {
      this.loading = true;
      this.searchWord = "";
      this.searchTableData = null;
      await this.lr_loadCompanys(false);
      this.loading = false;
    },

    hanleSearch() {
      if (this.searchWord) {
        this.searchTableData = this.lr_companyList.filter(
          (item) =>
            item.f_FullName.indexOf(this.searchWord) > -1 ||
            item.f_EnCode.indexOf(this.searchWord) > -1
        );
      } else {
        this.searchTableData = null;
      }
    },
    handleAdd() {
      this.formEdit = false;
      this.showForm("Add公司");
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm("Edit公司");
    },
    handleDelete($index, row) {
      this.$confirm(
        this.$t("This operation will permanently delete the data. Do you want to continue?"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(() => {
          api.remove(row.f_CompanyId).then(() => {
            this.$message({
              type: "success",
              message: this.$t("Delete  success"),
            });
            this.loadTable();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled"),
          });
        });
    },
    handleSave(showLoading, hideLoading) {
      this.$refs.form.validateForm(() => {
        showLoading();
        const formData = this.$refs.form.getForm();
        if (this.formEdit) {
          // 修改数据
          api
            .update(formData.f_CompanyId, formData)
            .then(() => {
              hideLoading();
              this.formVisible = false;
              this.$message({
                type: "success",
                message: this.$t("更新成功!"),
              });
              this.loadTable();
            })
            .catch(() => {
              hideLoading();
            });
        } else {
          // Edit data
          api
            .add(formData)
            .then(() => {
              hideLoading();
              this.formVisible = false;
              this.$message({
                type: "success",
                message: this.$t("添加成功!"),
              });
              this.loadTable();
            })
            .catch(() => {
              hideLoading();
            });
        }
      });
    },
    handleOpenedForm() {
      if (this.formEdit) {
        this.$refs.form.setForm(this.formEditRow);
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    //公司同步
    openFrom(){
        this.syncVisible = true
    },
    async handleSync(){
        this.$confirm(this.$t('此操作将开始同步用户信息, 是否继续?'), this.$t('Tips'), {
            confirmButtonText: this.$t('confirm'),
            cancelButtonText: this.$t('cancel'),
            type: 'warning'
        }).then(() => {
            this.syncVisible = false
            this.syncLoading = true
            api.syncData(this.startTime).then(()=> {
                this.$message({
                    type: 'success',
                    message: this.$t('同步成功!')
                })
                this.loadTable()
                this.syncLoading = false
            }).catch(() => {})
        }).catch(() => {
            this.$message({
                type: 'info',
                message: this.$t('已cancel同步')
            })        
        })
    }
  },
};
</script>
